import sqlite3
import time

from entity.Score import Score
from tool.my_uuid import get_uuid
import globals


class Ranking:
    def __init__(self, name, score):
        self.name = name
        self.score = str(score)

    def get_name(self):
        return self.name

    def get_score(self):
        return self.score


class Score_mapper:
    def __init__(self, db_path):  # 构造方法
        self.conn = sqlite3.connect(db_path)

    def __del__(self):  # 销毁勾子
        self.conn.close()

    def __value_to_ranking(self, value: list) -> list:
        result: list = []
        for v in value:
            result.append(Ranking(v[0], v[1]))
        return result

    def get_top10(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT user_name,MAX(score) max_score FROM score '
                       'GROUP BY user_name ORDER BY max_score DESC LIMIT 10')
        value = self.__value_to_ranking(cursor.fetchall())
        return value

    def save_score(self, user_name, score):
        cursor = self.conn.cursor()
        timestamp = int(time.time())
        uuid: str = get_uuid()
        print(uuid,user_name, score, timestamp)
        cursor.execute('INSERT INTO score (id, user_name, score, create_time) VALUES (?,?,?,?)',
                       (uuid, user_name, score, timestamp))
        self.conn.commit()

    def get_all_score_data(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT * FROM score')
        return cursor.fetchall()


if __name__ == '__main__':
    score_mapper = Score_mapper('../db/data.db')
    print(score_mapper.get_top10()[0].get_score())
